import {Component } from 'react';

class StudentInfo extends Component{

    constructor(props){
        super(props);
        this.state={
            datas:[
                {id:1,"name":"张三",age:19},
                {id:2,"name":"李四",age:20},
                {id:3,"name":"王五",age:30},
            ],
            ids:4,  //记录下一个学生的编号
            stundetName:"",
            stuAge:""
        }
    }

    handleStundetName=(e)=>{
        this.setState({
            stundetName:e.target.value
        })
    }

    handleStundetAge=(e)=>{
        this.setState({
            stuAge:e.target.value
        })
    }

    addStudent=()=>{
        //console.log(this.state.stundetName,this.state.stuAge)
        //创建一个学生对象
        let stuObj = {"id":this.state.ids,"name":this.state.stundetName,"age":this.state.stuAge}
        
        //把学生对象添加进数组中
        this.state.datas.push(stuObj);
    
        this.setState({
            datas:this.state.datas,
            ids:this.state.ids+1,
            stuAge:"",
            stundetName:""
        })
    }

    deleteStudent=()=>{
        this.state.datas.pop();
        this.setState({
            datas:this.state.datas
        })
    }

    render(){
        return(
            <>
            <div>
                <label>
                 姓名：<input value={this.state.stundetName} type='text' onChange={this.handleStundetName}></input>
                </label>
                <label>
                 年龄：<input value={this.state.stuAge} type='text' onChange={this.handleStundetAge} ></input>
                </label>
                <button onClick={this.addStudent}>添加</button>
                 <button onClick={this.deleteStudent}>删除</button>
            </div>
            <hr></hr>
            <div>
                <ul>
                {
                    this.state.datas.map(item=><li key={item.id}>{item.id}----{item.name}----{item.age}</li>)
                }
                </ul>
            </div>
            </>
        )
    }
}

export default StudentInfo 

